package gg.zsw.datasource.demo.kafka.config;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * kafka消费者配置
 */
@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    /**
     * kakfa服务节点配置
     */
    @Value("${kafka.consumer.bootstrap-servers}")
    private String bootstrapServers;

    /**
     * 是否自动提交消费偏移量
     */
    @Value("${kafka.consumer.enable.auto.commit:true}")
    private boolean enableAutoCommit;

    /**
     * 消费组ID
     */
    @Value("${kafka.consumer.group.id:group}")
    private String groupId;

    /**
     * 自动提交的时间间隔
     */
    @Value("${kafka.consumer.auto.commit.interval.ms:1000}")
    private int autoCommitInterval;

    /**
     * 批量消费时，一次获取的最大记录数
     */
    @Value("${kafka.consumer.max.poll.records:1000}")
    private int maxPollRecords;

    /**
     *  初始消费的偏移
     */
    @Value("${kafka.consumer.auto.offset.reset:latest}")
    private String autoOffsetReset;

    @Value("${kafka.consumer.key.deserializer:org.apache.kafka.common.serialization.StringDeserializer}")
    private String keyDeserializer;

    @Value("${kafka.consumer.value.deserializer:org.apache.kafka.common.serialization.StringDeserializer}")
    private String valueDeserializer;

    /**
     * 消费的并发数
     */
    @Value("${kafka.consumer.concurrency:4}")
    private int concurrency;

    /**
     * 消费数据时，最大的等待时间
     */
    @Value("${kafka.consumer.poll-timeout.ms:3000}")
    private long pollTimeout;

    @Value("${kafka.consumer.batch-listener:false}")
    private boolean batchListener;

    /**
     * 拦截器
     */
    @Value("${kafka.consumer.interceptor.classes:}")
    private String interceptorClasses;

    private Map<String, Object> consumerConfig() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords);
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializer);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer);
        if (interceptorClasses != null && interceptorClasses.trim().length() != 0) {
            String[] split = interceptorClasses.trim().split(",");
            props.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, Arrays.asList(split));
        }
        return props;
    }

    @Bean
    protected ConsumerFactory<Object, Object> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfig());
    }

    @Bean
    protected KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Object, Object>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<Object, Object> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        // 一定要定义批量消费接口，否则会出现错误
        factory.setBatchListener(batchListener);
        factory.setConcurrency(concurrency);
        factory.getContainerProperties().setPollTimeout(pollTimeout);
        factory.afterPropertiesSet();
        return factory;
    }




}
